package ssl;

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.io.*;
import java.net.*;
import java.security.*;
import java.util.*;
import javax.net.*;
import javax.net.ssl.*;
import javax.swing.*;

public class Client implements Runnable {
  private InputStream in;
  private OutputStream out;
  private KeyStore clientKeyStore;
  private KeyStore serverKeyStore;
  private SSLContext sslContext;
  private Set postings = new HashSet();
  private Font font = new Font( "TimesRoman", Font.PLAIN, 18 );
  static private final String passphrase = "clientpw";
  static private SecureRandom secureRandom;

  public Client( String host, int port ) {
    connect( host, port );
    new Thread( this ).start();
  }

  private void setupServerKeystore() throws GeneralSecurityException, IOException {
    serverKeyStore = KeyStore.getInstance( "JKS" );
    serverKeyStore.load( new FileInputStream( "server.public" ), 
                        "public".toCharArray() );
  }

  private void setupClientKeyStore() throws GeneralSecurityException, IOException {
    clientKeyStore = KeyStore.getInstance( "JKS" );
    clientKeyStore.load( new FileInputStream( "client.private" ),
                       passphrase.toCharArray() );
  }

  private void setupSSLContext() throws GeneralSecurityException, IOException {
    TrustManagerFactory tmf = TrustManagerFactory.getInstance( "SunX509" );
    tmf.init( serverKeyStore );

    KeyManagerFactory kmf = KeyManagerFactory.getInstance( "SunX509" );
    kmf.init( clientKeyStore, passphrase.toCharArray() );

    sslContext = SSLContext.getInstance( "TLS" );
    sslContext.init( kmf.getKeyManagers(),
                     tmf.getTrustManagers(),
                     secureRandom );
  }

  private void connect( String host, int port ) {
    try {
      setupServerKeystore();
      setupClientKeyStore();
      setupSSLContext();

      SSLSocketFactory sf = sslContext.getSocketFactory();
      SSLSocket socket = (SSLSocket)sf.createSocket( host, port );

      in = socket.getInputStream();
      out = socket.getOutputStream();

    } catch( GeneralSecurityException gse ) {
      gse.printStackTrace();
    } catch( IOException ie ) {
      ie.printStackTrace();
    }
  }

  public void run() {
	  Scanner scan = new Scanner(System.in);
      while (true) {
    	  String str = scan.nextLine();
    	  byte[] output = new byte[str.length()];
    	  char[] tmp = str.toCharArray();
    	  for (int i=0; i<str.length(); ++i) {
    		  output[i] = (byte)tmp[i];
    	  }
    	  try {
			out.write(output);
		} catch (IOException e) { e.printStackTrace(); }
      }
  }
  
  static public void main( String args[] ) {
    String host = "localhost";
    int port = 4545;

    System.out.println( "Wait while secure random numbers are initialized...." );
    secureRandom = new SecureRandom();
    secureRandom.nextInt();
    System.out.println( "Done." );

    new Client( host, port );
  }
}
